package main

import (
	"crypto/rand"
	"math/big"
	"time"
)

const (
	adminPassword  = "Yixin@112233" // 管理口令
	dhcpConfig     = "/etc/config/dhcp"
	dhcpLeases     = "/tmp/dhcp.leases"
	netArp         = "/proc/net/arp"
	arpbindConfig  = "/etc/config/arpbind"
	passwallConfig = "/etc/config/passwall"

	//dhcpConfig     = "./test/dhcp"
	//dhcpLeases     = "./test/dhcp.leases"
	//netArp         = "./test/arp"
	//arpbindConfig  = "./test/arpbind"
	//passwallConfig = "./test/passwall"

	Dictionary = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
)

// 设备结构体
type Device struct {
	MAC    string `json:"mac"`
	Name   string `json:"name"`
	IP     string `json:"ip"`
	Type   string `json:"type"`   // static or dynamic
	Status string `json:"status"` // online or offline
}

// 代理节点结构体
type Node struct {
	ID       string   `json:"id"`
	Name     string   `json:"name"`
	Address  string   `json:"address"`
	Port     int      `json:"port"`
	Username string   `json:"username,omitempty"`
	Password string   `json:"password,omitempty"`
	Devices  []Device `json:"devices"` // 绑定设备
}

// 绑定结构体
type Binding struct {
	ID         string `json:"id"`
	NodeID     string `json:"nodeId"`
	NodeName   string `json:"nodeName"`
	DeviceName string `json:"deviceName"`
	DeviceMAC  string `json:"deviceMac"`
	DeviceIP   string `json:"deviceIp"`
	Remarks    string `json:"remarks"`
	Status     bool   `json:"status"`
}

// 分页响应
type PaginatedResponse struct {
	Total int         `json:"total"`
	Page  int         `json:"page"`
	Size  int         `json:"size"`
	Data  interface{} `json:"data"`
}

// Rand 生成 0 ~ n-1 的随机数
func Rand(n int) int {
	if n <= 0 {
		return 0
	}
	num, _ := rand.Int(rand.Reader, big.NewInt(int64(n)))
	return int(num.Int64())
}

/**
 * 创建随机字符串
 * @params num int 字符数量
 * @return string
 */
func CreateCode(num int) (str string) {
	chars := []byte(Dictionary)
	strArr := make([]byte, num)
	for i := 0; i < num; i++ {
		strArr[i] = chars[Rand(len(chars)-1)]
	}
	return string(strArr)
}

func cacheCleanup() {
	deviceTimeout = time.UnixMilli(0)
	configBuffer.Delete(dhcpConfig)
	configBuffer.Delete(arpbindConfig)
	configBuffer.Delete(passwallConfig)
}

var loginFailedCount = 0 // 登录失败次数
var loginTokens []*Token

type Token struct {
	Token   string    `json:"token"`
	Timeout time.Time `json:"timeout"`
}

func TokenCheck(token string) bool {
	now := time.Now()
	for _, t := range loginTokens {
		if t.Token == token && t.Timeout.After(now) {
			t.Timeout = now.Add(time.Hour)
			return true
		}
	}
	return false
}

func TokenCleanup() {
	defer time.AfterFunc(time.Minute, TokenCleanup)
	var tokens []*Token
	now := time.Now()
	for _, t := range loginTokens {
		if t.Timeout.After(now) {
			tokens = append(tokens, t)
		}
	}
	loginTokens = tokens
}

func init() {
	TokenCleanup()
}
